package marcis.jarina.directory;


import org.apache.log4j.Logger;

import java.io.*;
import java.util.Collection;


/**
 * @author jan.marcis
 */
public class FileHelper {

    private static final Logger log = Logger.getLogger("marcis.jarina.FileHelper");

    public static boolean match(Collection<String> imports, Collection<String> containedClasses) {
        if (imports == null || imports.size() == 0 || containedClasses == null || containedClasses.size() == 0) {
            return false;
        }
        for (String imp : imports) {
            if (containedClasses.contains(imp)) {
                return true;
            }
        }
        return false;
    }

    public static File getPomFromJar(File jar) {
        File pom = new File(jar.getParentFile(), extractFileNameWithoutExt(jar) + ".pom");
        if (pom.exists()) {
            return pom;
        }
        return null;
    }

    public static File getJarFromPom(File pom) {
        File jar = new File(pom.getParentFile(), extractFileNameWithoutExt(pom) + ".jar");
        if (jar.exists()) {
            return jar;
        }
        return null;
    }

    private static String extractFileNameWithoutExt(File file) {
        return file.getName().substring(0, file.getName().lastIndexOf("."));
    }

    public static void backupFile(File original) {
        int i = 0;
        File backupOrig = null;
        do {
            backupOrig = new File(original.getParent(), extractFileNameWithoutExt(original) + "_" + i + ".bak");
            i++;
        } while (backupOrig.exists());
        try {
            copyFile(original, backupOrig);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    private static void copyFile(File original, File backupOrig) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(original));
        BufferedWriter bw = new BufferedWriter(new FileWriter(backupOrig));
        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
        }
        bw.flush();
        bw.close();
        br.close();
    }

}
